const fs = require('fs');
const path = require('path');
let _self;
class FileOp{
    constructor(){
        _self = this;
    }
    async makeDir(dirpath,dirname){
        if (!fs.existsSync(dirpath)) {
            fs.mkdirSync(dirpath);
            return true;
        }else{
            return false;
        }
    }

    async existsDir(dir){
        return await fs.existsSync(dir);
    }

    async upload(files,dir){
        const tmpdir = dir;
        const fileStats = [];
        for(let key in files){
            const file = files[key];
            const filePath = path.join(tmpdir,file.name);
            const reader = fs.createReadStream(file.path);
            const writer = fs.createWriteStream(filePath);
            reader.pipe(writer);
            fileStats.push({
                filename:file.name,
                filepath:filePath,
                filetype:file.type,
                filesize:file.size
            });
        }
        return fileStats;
    }

    async deleteFile(p){
        if (!p.startsWith('/')){
            p = `/${p}`;
        }
        p = path.join(__dirname,`../public${p}`);
        if(fs.existsSync(p) ) {
            let stats = fs.statSync(p);
            let isFile = stats.isFile();//是文件  
            if(isFile){
                fs.unlinkSync(p);
            }else{
                var files = [];
                if(fs.existsSync(p) ) {
                    files = fs.readdirSync(p);
                    files.forEach(function(file,index){
                        var curPath = path.join(p,file);
                        if(fs.statSync(curPath).isDirectory()) {
                            _self.deleteFolder(curPath);
                        } else {
                            fs.unlinkSync(curPath);
                        }
                    });
                    fs.rmdirSync(p);
                }
            }
        }
        
    }

    async renameFile(oldPath,newPath){
        console.log(`old=${oldPath},new=${newPath}`)
        if(fs.existsSync(oldPath)){
            console.log(oldPath);
            fs.renameSync(oldPath, newPath);
            return true;
        }else{
            return false;
        }
    }
}


module.exports = new FileOp();